var express = require('express');
var router = express.Router();

const DepartmentModel = require('../db/DepartmentModel');
const UserModel = require('../db/UserModel');//用户模型
const OperationLog = require("../db/OperationLog");
const moment = require('moment');
const now = () => {
    return moment().format('YYYY-MM-DD HH:mm:ss')
}
const Fun = require("../middlewares/Fun")
/***
 *  list 科室列表
 *  one 查找科室
 *  save 新建科室
 *  update 更新科室
 *  delete 删除科室
 */



router.post('/hadnamed', function (req, res, next) {
    if (!req.body.name) {
        return res.json({ code: 201, mes: '缺少必填信息！' });
    }

    DepartmentModel.findOne({ name: req.body.name }).then((data) => {
        if (data) {
            return res.json({ code: 201, mes: '该名称已经存在！' });
        } else {
            return res.json({ code: 200, mes: '该名称可用！' });
        }
    }).catch(() => {
        return res.json({ code: 201, mes: '发生意外错误！' })
    });

});


// 保存门店

router.post('/save', function (req, res, next) {
    let pare;
    let user = req.user;
    // 获取条件
    if (req.body.id) {
        if (!req.body.id || !req.body.name || !req.body.state || !req.body.grade) {
            return res.json({ code: 201, mes: "缺少必填信息！" })
        }
        const id = req.body.id;
        const name = req.body.name;
        const state = req.body.state;
        const grade = req.body.grade;
        DepartmentModel.findById(id).then((department) => {
            if (department) {
                return DepartmentModel.findOne({ name: req.body.name }).then((data) => {
                    if (!data) {
                        const departmentdb = new DepartmentModel({ name, state, grade, id });
                        return departmentdb.save().then((department) => {
                            return DepartmentModel.update({ _id: id }, { $push: { son: department._id } })
                        }).then((data) => {
                            console.log(data);
                            pare = {
                                id: user._id,
                                name: user.name,
                                roles: user.role,
                                ip: req.ip.replace(/::ffff:/, ''),
                                time: now(),
                                Operationcontent: "创建科室成功"
                            };
                            OperationLog.create(pare).then(data => { }).catch(e => { })
                            return res.json({ code: 200, mes: '创建科室成功' })
                        }).catch((err) => {
                            console.log(err);
                            pare.time = now();
                            pare.Operationcontent = "创建科室失败";
                            OperationLog.create(pare).then(data => { }).catch(e => { })
                            return res.json({ code: 201, mes: '发生意外错误！' })
                        });
                    } else {
                        return res.json({ code: 201, mes: '科室名称已经存在' });
                    }
                })
            } else {
                return res.json({ code: 201, mes: "id传递有误！" });
            }
        }).catch((err) => {
            console.log(err);
            return res.json({ code: 201, mes: '发生意外错误！' })
        });
    } else {
        if (!req.body.grade || !req.body.state || !req.body.name) {
            return res.json({ code: 201, mes: '缺少必填信息！' });
        }
        const department = new DepartmentModel(req.body);
        DepartmentModel.find({ name: req.body.name }).then((data) => {
            if (data.length != 0) { return res.json({ code: 201, mes: '科室名称已经存在' }); }
            else {
                department.save().then(() => {
                    pare = {
                        id: user._id,
                        name: user.name,
                        roles: user.role,
                        ip: req.ip.replace(/::ffff:/, ''),
                        time: now(),
                        Operationcontent: "创建科室成功"
                    };
                    OperationLog.create(pare).then(data => { }).catch(e => { })
                    return res.json({ code: 200, mes: '创建科室成功' })
                }).catch(() => {
                    pare.time = now();
                    pare.Operationcontent = "创建科室失败";
                    OperationLog.create(pare).then(data => { }).catch(e => { })
                    return res.json({ code: 201, mes: '发生意外错误！' });
                });
            }
        }).catch((err) => {
            console.log(err);
            return res.json({ code: 201, mes: '发生意外错误！' })
        });
    }
});
// 更新科室信息
router.post('/update', function (req, res, next) {
    // 更改密码的判断需要额外处理
    const set = {};
    if (req.body.name) {
        set.name = req.body.name;
    }
    if (req.body.state) {
        set.state = req.body.state;
    }
    const id = req.body.id;
    DepartmentModel.findById(id).then(
        (data) => {
            if (data == null) { return res.json({ code: 201, mes: '传入id错误' }); }
            else {
                return DepartmentModel.update({ _id: id }, { $set: set }).then(
                    () => { return res.json({ code: 200, mes: '更改成功' }); }
                ).catch(() => {
                    return res.json({ code: 201, mes: '更改失败！' })
                });
            }
        }
    ).catch(function (err) {
        console.log(err);
        return res.json({ code: 201, mes: '发生意外错误！' });
    });
});
// 查找所有科室
router.get('/list', function (req, res, next) {
    DepartmentModel.find({}).then((department) => {
        return res.json({ code: 200, department });
    }).catch(() => {
        return res.json({ code: 201, mes: '发生意外错误！' });
    });
});
// 查找指定科室
router.get('/one/:id', function (req, res, next) {
    const id = req.params.id;
    DepartmentModel.findById(id).then((department) => {
        return res.json({ code: 200, department });
    }).catch(() => {
        return res.json({ code: 201, mes: '发生意外错误！' });
    });
});
// 删除科室接口
router.post('/delete', function (req, res, next) {
    const id = req.body.id;
    let user=req.user
    DepartmentModel.findById(id).then((data) => {
        if (data.grade == 1) {
            data.son.push(id);
            return DepartmentModel.remove({ _id: data.son }).then(() => {
                Fun.saveLogs(user, req.ip.replace(/::ffff:/, ''), "删除科室成功");
                return res.json({ code: 200, mes: '删除成功！' });
            });

        } else {
            DepartmentModel.remove({ _id: id }).then((data) => {

                return DepartmentModel.findOne({ son: id });
            }).then((data) => {
                if (data != null) {

                    return DepartmentModel.update({ _id: data._id }, { $pull: { son: id } }).then(() => {
                        return res.json({ code: 200, mes: '删除成功！' });
                    });

                } else {
                    return res.json({ code: 200, mes: '删除成功！' });
                }
            });
        }
    }).catch(() => {
        return res.json({ code: 201, mes: '发生意外错误！' });
    });
});

router.post('/hasdoctors', function (req, res, next) {
    const id = req.body.id;
    DepartmentModel.findById(id).then((data) => {
        if (data.son.length != 0) { // 有子科室
            data.son.push(id);
            return UserModel.find({ department: { $in: data.son } }).then((data) => {
                if (data.length != 0) {
                    return res.json({ code: 201, mes: '该部门下有关联医生！' });
                } else {
                    return res.json({ code: 200, mes: '该部门下没有关联的医生！' });
                }
            });
        } else {
            return UserModel.find({ department: id }).then((data) => {
                if (data.length != 0) {
                    return res.json({ code: 201, mes: '该部门下有关联医生！' });
                } else {
                    return res.json({ code: 200, mes: '该部门下没有关联的医生！' });
                }
            });
        }
    }).catch(() => {
        return res.json({ code: 203, mes: '发生意外错误！' });
    });
});
module.exports = router;
